import sympy as sp
import numpy as np
import matplotlib.pyplot as plt

#支持中文
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']
# 支持负数
plt.rcParams['axes.unicode_minus'] = False

# 定义函数
def f(x):
    return x**2 - 3*x

# 符号计算
x = sp.symbols('x')
f_sym = x**2 - 3*x
f_prime = sp.diff(f_sym, x)

print("函数f(x)的导数是:", f_prime)

# 求临界点
critical_points = sp.solve(f_prime, x)
print("临界点是:", critical_points)

# 判断单调性
test_points = [0, 2]  # 在临界点两侧取测试点
for point in test_points:
    deriv_value = f_prime.subs(x, point)
    if deriv_value > 0:
        print(f"在x={point}处，导数为{deriv_value}，函数单调递增")
    else:
        print(f"在x={point}处，导数为{deriv_value}，函数单调递减")

# 可视化
x_vals = np.linspace(-1, 4, 100)
y_vals = [f(val) for val in x_vals]
dy_vals = [2*val - 3 for val in x_vals]  # 导数函数值

plt.figure(figsize=(12, 5))

plt.subplot(1, 2, 1)
plt.plot(x_vals, y_vals, 'b-', linewidth=2, label='f(x) = x² - 3x')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.grid(True, alpha=0.3)
plt.legend()

plt.subplot(1, 2, 2)
plt.plot(x_vals, dy_vals, 'r-', linewidth=2, label="f'(x) = 2x - 3")
plt.axhline(y=0, color='k', linestyle='--', alpha=0.5)
plt.xlabel('x')
plt.ylabel("f'(x)")
plt.grid(True, alpha=0.3)
plt.legend()

plt.tight_layout()
plt.show()